(function(angular) {
	'use strict';
	angular.module('fs.waf').controller('apf.buyBack.createContinueController', createContinueController);
	createContinueController.$inject = [ '$q', '$filter', '$scope', 'Constants', 'formatService', 'modalService', 'gridService', 'layoutConfig', 'validatorConfig', 'authService',
			'buyBackService', 'dateService', "arithService", 'commonService'];
	function createContinueController($q, $filter, $scope, Constants, formatService, modalService, gridService, layoutConfig, validatorConfig, authService, buyBackService, dateService, arithService, commonService) {
		var ctrl = this, params = $scope.$stateParams.params;
		ctrl.layoutConfig = layoutConfig;
		ctrl.validatorConfig = validatorConfig;
		ctrl.invPayLoad = {};
		ctrl.init = function() {
			ctrl.calendarCodes = ['S:' + $scope.site.siteCode];
			buyBackService.getCurrencyOptions().then(function(response) {
				ctrl.currencyOptions = response.data;
			});
			ctrl.innerGridOptions = gridService.createInnerGridOptions($scope, ctrl.layoutConfig.formConfigs.pisCfg.tableConfigs.table, rowSelectionChanged);
			ctrl.innerGridOptions.data = 'vm.invPayLoad.piList';
			authService.createContinue(params).then(function(response) {
				if (response.data && response.data.model && response.data.task) {
					ctrl.invPayLoad= response.data.model;
					ctrl.invPayLoad.taskId = response.data.task.taskId;
				}
			});
		};
	
		
		ctrl.changePipayAmt = function(value, formCtrl, isInitialized){
			if(!isInitialized){
				ctrl.invPayLoad.totalPayAmount = buyBackService.calTotalPayAmount(ctrl.invPayLoad.piList);
			}
		};
		
		ctrl.addPi = function(row){
			var deferred = $q.defer(), params = {};
			var promise = deferred.promise;
			if(!ctrl.invPayLoad.sellerCode){
				deferred.reject();
				modalService.openErrorDialogs({
					'messages' : ["title.dialogs.info.sellercode.required"]
				});
			}else{
				params.piIds = [];
				params.sellerCode = $filter('encode')(ctrl.invPayLoad.sellerCode);
				params.dataType = "INVOICE-PAYMENT-BATCH";
				params.payCcy = ctrl.invPayLoad.payCcy;
				angular.forEach(ctrl.invPayLoad.piList, function(pi, index) {
					params.piIds.push($filter('encode')(pi.piId));
				});
				modalService.openCustomDialogs({
					'dialogsModule' : 'apf.pi',
					'title' : 'title.dialogs.lookup',
					'params' : params,
					"size" : [ 1234 ],
					'btnCallback' : {
						'ok' : function(selectedRows) {
							if (!selectedRows || selectedRows.length == 0) {
								modalService.openErrorDialogs({
									messages : [ 'title.dialogs.info.norecsel' ]
								});
							}else{
								angular.forEach(selectedRows, function(pi, index) {
									pi.pipayAmt = pi.piOutsAmt;
									pi.dataStatus = "C";
									ctrl.invPayLoad.piList.push(pi);
								});
								ctrl.invPayLoad.totalPayAmount = buyBackService.calTotalPayAmount(ctrl.invPayLoad.piList);
								ctrl.invPayLoad.totalPiAmt = buyBackService.calTotalPiAmt(ctrl.invPayLoad.piList);
								
							}
							deferred.reject();
						},
						'close' : function(){
							deferred.reject();
						}
					}
				});
			}
			return promise;
		};
		
		ctrl.removePi = function(){
			ctrl.invPayLoad.totalPayAmount = buyBackService.calTotalPayAmount(ctrl.invPayLoad.piList, ctrl.selectedPis);
			ctrl.invPayLoad.totalPiAmt = buyBackService.calTotalPiAmt(ctrl.invPayLoad.piList, ctrl.selectedPis);
		};
		

		ctrl.createContinueSave = function() {
			if (!ctrl.invPayLoad.piList || ctrl.invPayLoad.piList.length == 0) {
				modalService.openErrorDialogs({
					messages : [ 'title.dialogs.pi.norecsel' ]
				});
				return false;
			}
			return authService.createContinueSave(ctrl.invPayLoad).then(saveSuccessful, saveFailed);
		};

		ctrl.createContinueCancel = function() {
			modalService.openConfirmDialogs({
				'messages' : [ {msg : 'title.dialog.confirm.cancel', args : [ctrl.invPayLoad.primaryKey]} ],
				'btnCallback' : {
					'ok' : function() {
						authService.createContinueCancel(ctrl.invPayLoad).then(cancelSuccessful, cancelFailed);
					}
				}
			});
		};

		function saveSuccessful(response) {
			modalService.openInfoDialogs({
				'messages' : [ 'title.dialog.successful.save' ]
			});
			if (response.data && response.data.model) {
				angular.extend(ctrl.invPayLoad, response.data.model);
			}else if (response.data.task && response.data.task.taskId) {
				authService.saveSuccessfulProcess(response.data.task).then(function(response) {
					var routerInfo = response.data || {}, state = routerInfo.processState;
					delete routerInfo.processState;
					$scope.go(state, routerInfo);
				}, angular.noop);
			}
		}

		function saveFailed(response) {
			modalService.openErrorDialogs({
				'messages' : response.error
			});
		}
		
		function cancelSuccessful(response) {
			modalService.openAcknowledgeDialogs({
				'messages' : [ 'title.dialog.successful.cancel' ],
				'btnCallback' : {
					'close' : function() {
						$scope.go('apf.workflow.wfTxn.list');
					}
				},
				'redirections' : [ {
					'name' : 'title.infobar.workflow.list',
					'state' : 'apf.workflow.wfTxn.list',
					'params' : {}
				}, {
					'name' : 'title.infobar.buyback.create',
					'state' : 'apf.buyBack.create',
					'params' : {}
				}]
			});
		}

		function cancelFailed(response) {
			modalService.openErrorDialogs({
				'messages' : response.error
			});
		}	
		function rowSelectionChanged(eventRow, selectedRows) {
			ctrl.selectedPis = selectedRows;
		}
		
		ctrl.createContinuePreview = function() {
			if (!ctrl.invPayLoad.piList || ctrl.invPayLoad.piList.length == 0) {
				modalService.openErrorDialogs({
					messages : [ 'title.dialogs.pi.norecsel' ]
				});
				return false;
			}
			return authService.createContinuePreview(ctrl.invPayLoad).then(previewSuccessful, previewFailed);
		};
		
		function previewSuccessful(response) {
			if (response.data && response.data.model) {
				var invPayLoad = response.data.model;
				invPayLoad.taskId = ctrl.invPayLoad.taskId;
				var params = {
						'invPayLoad' : invPayLoad
				};
				$scope.go('apf.buyBack.createContinuePreview',params);
			}
		}
		
		function previewFailed(response) {
			modalService.openErrorDialogs({
				'messages' : response.error
			});
		}
	}
})(angular);
